package art_of_java_concurrent_programming.lock.downgrade;

import art_of_java_concurrent_programming.lock.read_write_lock.Cache;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 降级锁: 锁降级是指把持住（当前拥有的）写锁，再获取到读锁，随后释放（先前拥有的）写锁的过程。
 * @author lixiangke
 * @date 2018/1/30
 */
public class DowngradeLock {

    /**
     * 当数据发生变更后，被设置为false
     */
    volatile boolean update = false;

    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    Lock readLock = lock.readLock();
    Lock writeLock = lock.writeLock();

    public void processData() {
        readLock.lock();
        if (!update) {
            // 必须先释放读锁
            readLock.unlock();
            // 锁降级从写锁获取到开始
            writeLock.lock();
            try {
                if (!update) {
                    // 准备数据的流程（略）
                    update = true;
                }
                readLock.lock();
            } finally {
                writeLock.unlock();
            }
            // 锁降级完成，写锁降级为读锁
        }
        try {
            // 使用数据的流程（略）

        } finally {
            readLock.unlock();
        }
    }
}
